package cn.com.surker.task;

import cn.com.surker.lab.service.impl.ErpLabExpendBImpl;
import cn.com.surker.redis.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.transaction.RollbackException;

/**
 * @Author lucky
 * @create 2025年03月29 8:33
 * @desc
 */
@Slf4j
@Configuration
@EnableScheduling
public class LabTask {

    /**计算购进报表redis锁**/
    private final static String MATERIAL_WEIGHT_REDIS_LOOK_KEY = "MATERIAL_WEIGHT_REDIS_LOOK_KEY";
    @Resource
	private ErpLabExpendBImpl expendBService;
    @Value("${erp.datasource.erp.db}")
    protected String erpDb;
    @Resource
    private RedisUtils redisUtils;

    @Scheduled(cron = "43 2/10 * * * ?")
    @Transactional(rollbackFor = RollbackException.class,propagation = Propagation.REQUIRED)
    public void billReportTime() {
        System.out.println("开始计算B库消耗");
        Boolean looked = redisUtils.hasLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);//获取锁是否存在
        try {
            if (!looked) {
                expendBService.calcBExpend(erpDb, null, null);
                redisUtils.acquireLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);//不存在枷锁
            } else {
                Thread.sleep(300L);
                looked = redisUtils.hasLock(MATERIAL_WEIGHT_REDIS_LOOK_KEY);//获取锁是否存在
                if (!looked) {
                    expendBService.calcBExpend(erpDb, null, null);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
